package mapspinner.persistence.disk;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import mapspinner.TerrainKey;
import mapspinner.persistence.TerrainPersistence;
import mapspinner.persistence.datatypes.TerrainData;
import mapspinner.persistence.datatypes.TerrainSettings;

import com.jme.util.export.binary.BinaryExporter;
import com.jme.util.export.binary.BinaryImporter;

public class DiskPersistence implements TerrainPersistence {
	public static boolean useSavables = true;

	@Override
	public TerrainSettings getSettings(final String directory) throws Exception {
		final File dataFile = new java.io.File(directory + "/terrain.cfg");
		if (!dataFile.exists())
			return null;
		Object data = null;
		if (useSavables) {
			final BinaryImporter bi = new BinaryImporter();
			data = bi.load(dataFile);
		} else {
			final FileInputStream fis = new FileInputStream(dataFile);
			final ObjectInputStream ois = new ObjectInputStream(fis);
			data = ois.readObject();
		}
		if (data != null && data instanceof TerrainData)
			return (TerrainSettings) data;
		return null;
	}

	public TerrainData getTerrainData(final TerrainKey key,
			final String directory) throws IOException, ClassNotFoundException {
		final File dataFile = new java.io.File(directory + "/("
				+ String.valueOf(key.hashCode() + ").map"));
		if (!dataFile.exists())
			return null;
		Object data = null;
		if (useSavables) {
			final BinaryImporter bi = new BinaryImporter();
			data = bi.load(dataFile);
		} else {
			final FileInputStream fis = new FileInputStream(dataFile);
			final ObjectInputStream ois = new ObjectInputStream(fis);
			data = ois.readObject();
		}
		if (data != null && data instanceof TerrainData)
			return (TerrainData) data;
		return null;
	}

	@Override
	public void setSettings(final String directory,
			final TerrainSettings settings) throws Exception {
		final File dataFile = new java.io.File(directory + "/terrain.cfg");
		if (useSavables) {
			final BinaryExporter be = new BinaryExporter();
			be.save(settings, dataFile);
		} else {
			final FileOutputStream fos = new FileOutputStream(dataFile);
			final ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(settings);
		}
	}

	public void setTerrainData(final TerrainKey key, final TerrainData mapData,
			final String directory) throws IOException, ClassNotFoundException {
		final File dataFile = new java.io.File(directory + "/("
				+ String.valueOf(key.hashCode() + ").map"));
		if (useSavables) {
			final BinaryExporter be = new BinaryExporter();
			be.save(mapData, dataFile);
		} else {
			final FileOutputStream fos = new FileOutputStream(dataFile);
			final ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(mapData);
		}
	}
}
